/// <reference path="../../../typings/index.d.ts" />
import { navigateToMap, chooseLocation } from './getLocation';
import * as dao from "../dao/dbAccess";

var WXAPP = getApp();
wx.cloud.init();
const db = wx.cloud.database();
const _ = db.command;

Page({

  backFromMap: false,       // 从地图回来的

  data: {
    BtnOrderText: '预约',     // 预约按钮的文本
    isOrdered: false,          // 预约后显示页面的其余元素
    canPressOrder: true,      // 防止连续点击预约按钮，表示是否允许Visible值变化
    isHideOrderButton: false, // 隐藏预约按钮
    locationName: "",        // 地点名
    locationAddress: "",      // 地址
    floor: 0,                 // 宿舍楼层
    floorArray: ["未选", 1, 2, 3, 4, 5, 6],  // 楼层数组
    personCount: 0,          // 前面还有几人
    orderID: '',               // 订单ID
    waitTime:0,             //预计等待时间
    backed:false,
  },

  onLoad() {
    if (WXAPP.globalData.chooseLocation) {
      this.setData({
        locationName: WXAPP.globalData.chooseLocation.name,
        locationAddress: WXAPP.globalData.chooseLocation.address,
      });
    }
    if (WXAPP.globalData.domitoryInfo.floor != -1) {
      this.setData({
        floor: WXAPP.globalData.domitoryInfo.floor
      });
    }
    this.watchPersonCount();
  },

  onShow() {
    console.log('检查数据库状态')
    db.collection('orderStatus')
      .doc(WXAPP.globalData.openid)
      .get()
      .then(res => {
        this.setData({
          isOrdered: res.data.isOrdered,
          canPressOrder: res.data.canPressOrder,
          isHideOrderButton: res.data.isHideOrderButton,
          orderID: res.data.orderID
        })
        console.log('isordered    ' + this.data.isOrdered);
        console.log('canpress     ' + this.data.canPressOrder);
        console.log('ishiden     ' + this.data.isHideOrderButton);
        console.log("orderID: ", this.data.orderID);
      })


    db.collection("NWPU-Queue")
      .doc(WXAPP.globalData.domitoryInfo.name)
      .get()
      .then(res => {
        console.log('test UI')
        let queue = res.data[WXAPP.globalData.domitoryInfo.floor];
        console.log(queue.length);

        if (queue.length != 0) {
          db.collection("orderStatus")
            .doc(WXAPP.globalData.openid)
            .update({
              data:{
 predit: Math.floor(queue.length * 1.677 + Math.random() * 5)
              }
            })
        }
      })


    if (this.backFromMap) {//从地图中获取位置并成功返回则在前端界面上进行展示
      this.backFromMap = false;
      if (chooseLocation.getLocation()) {
        WXAPP.globalData.chooseLocation = chooseLocation.getLocation();
        this.setData({
          locationName: WXAPP.globalData.chooseLocation.name,
          locationAddress: WXAPP.globalData.chooseLocation.address
        });
        this.resolveDomitoryName(this.data.locationName);
        dao.pushUserLocation(WXAPP.globalData.chooseLocation);
        console.log(WXAPP.globalData.chooseLocation);
      }
      
      this.setData({
        backed:true
      })

    }
  },

  /**
   * 与选择楼层picker绑定的函数
   */
  onPickerChooseFloorChange(e) {
    if (!WXAPP.globalData.isLogin) {
      wx.showToast({
        title: '请登录后再选择',
        icon: 'none',
        duration: 1000
      })
    }else{
    this.setData({
      floor: e.detail.value
    });
    WXAPP.globalData.domitoryInfo.floor = this.data.floor;
    dao.pushUserDomitoryInfo(WXAPP.globalData.domitoryInfo);

    if(this.data.backed){
      db.collection("NWPU-Queue")
        .doc(WXAPP.globalData.domitoryInfo.name)
        .get()
        .then(res => {
          console.log('test UI')
          let queue = res.data[WXAPP.globalData.domitoryInfo.floor];
          console.log(queue.length);

          if (queue.length != 0) {
            this.setData({
              personCount: queue.length,
              waitTime: Math.floor(queue.length * 1.677 + Math.random() * 5)
            });

            db.collection("orderStatus")
            .doc(WXAPP.globalData.openid)
            .update({
              data:{
                predit: Math.floor(queue.length * 1.677 + Math.random() * 5)
              }
            })

          }
        })
    }

    }
  },

  /**
   * 从地址名字中解析宿舍名字，并存储到`app.globalData.domitoryInfo`中
   */
  resolveDomitoryName(locationName) {
    let regExp = new RegExp("[星云]天苑-?[A-F]");
    let res = regExp.exec(locationName);
    if (res) {
      WXAPP.globalData.domitoryInfo.name = res[0][0];
      if (res[0][3] == '-') {
        WXAPP.globalData.domitoryInfo.name += res[0][4];
      } else {
        WXAPP.globalData.domitoryInfo.name += res[0][3];
      }
      dao.pushUserDomitoryInfo(WXAPP.globalData.domitoryInfo);
    } else {
      wx.showToast({
        title: '选择的不是宿舍地址，请重新选择',
        icon: 'none',
        duration: 2000
      });
    }

  },

  onClickOrder() {
    if (!WXAPP.globalData.isLogin) {
      wx.showToast({
        title: '请登录后预约',
        icon: 'none',
        duration: 1000
      })
    }
    else {//用户已经成功登陆

      if (WXAPP.globalData.domitoryInfo.floor == 0) {
        wx.showToast({
          title: '请选择宿舍楼层',
          icon: 'none',
          duration: 2000
        });
      } else {
        WXAPP.globalData.orderShow = true;//在我的界面中展示当前预约的订单
        var that = this;
        if (this.data.canPressOrder == true) {
          this.setData({
            isOrdered: !this.data.isOrdered
          })
          wx.cloud.callFunction({
            name: 'updateStatus',
            data: {
              _id: WXAPP.globalData.openid,
              canPressOrder: that.data.canPressOrder,
              isHideOrderButton: true,
              isOrdered: that.data.isOrdered,
              orderNow: true,
            }
          })
        }
        //TODO 去掉按钮背景颜色
        this.setData({
          BtnOrderText: '预约成功！',
          canPressOrder: false
        });

        // db.collection('userInfo')
        //   .where({
        //     _openid: WXAPP.globalData.openid
        //   })
        //   .get()
        //   .then(cre => {
        //     wx.cloud.callFunction({
        //       name: 'updateCredit',
        //       data: {
        //         _id: WXAPP.globalData.openid,
        //         credit: Math.min(cre.data[0].credit + 1, 3)//信用分的上限是3
        //       }
        //     })
        //     console.log(cre.data[0].credit);
        //   })

        wx.cloud.callFunction({
          name: 'updateStatus',
          data: {
            _id: WXAPP.globalData.openid,
            canPressOrder: this.data.canPressOrder,
            isHideOrderButton: true,
            isOrdered: this.data.isOrdered,
            orderNow: true
          }
        })
        console.log('isordered    ' + that.data.isOrdered);
        console.log('canpress     ' + that.data.canPressOrder);
        console.log('ishiden     ' + that.data.isHideOrderButton);

        wx.showToast({
          title: '预约成功',
          icon: 'success',
          duration: 1000
        })
        //给历史订单数据库中添加数据
        wx.cloud.callFunction({
          name: 'addOrderHistory',
          data: {
            userID: WXAPP.globalData.openid,
            domitory: WXAPP.globalData.domitoryInfo.name,
            floor: WXAPP.globalData.domitoryInfo.floor
          }
        }).then(res => {
          console.log('历史订单添加成功', res);
          this.data.orderID = res.result._id;
          db.collection("orderStatus")
            .doc(WXAPP.globalData.openid)
            .update({
              data: {
                orderID: this.data.orderID
              }
            });
          wx.cloud.callFunction({
            name: "insertToQueue",
          }).then(res => {
            console.log("success insert to queue\n", res);
          }).catch(err => {
            console.error("fail insert to queue\n", err);
          })
        }).catch(err => {
          console.error("fail add order history\n", err)
        });

      }
    }
  },

  onClickCancel() {
    var that = this;
    wx.showModal({
      title: '取消预约',
      content: '确认取消当前预约？\r\n(取消预约会降低信用分)',
      success(res) {
        if (res.confirm) {
          that.setData({
            BtnOrderText: '预约',
            canPressOrder: true,
            isHideOrderButton: false,
            isOrdered: false
          });
          wx.cloud.callFunction({
            name: 'updateStatus',
            data: {
              _id: WXAPP.globalData.openid,
              canPressOrder: that.data.canPressOrder,
              isHideOrderButton: that.data.isHideOrderButton,
              isOrdered: that.data.isOrdered,
              orderNow: false
            }
          });

          db.collection('userInfo')
            .where({
              _openid: WXAPP.globalData.openid
            })
            .get()
            .then(cre => {
              wx.cloud.callFunction({
                name: 'updateCredit',
                data: {
                  _id: WXAPP.globalData.openid,
                  credit: Math.max(cre.data[0].credit - 1,0)
                }
              })
            })


          wx.cloud.callFunction({
            name: 'sortOrderHistory',
            data: {
              openid: WXAPP.globalData.openid
            }
          }).then(ord => {
            wx.cloud.callFunction({
              name: "removeFromQueue"
            }).then(res => {
              console.log("success remove from queue\n", res);
              wx.cloud.callFunction({
                name: 'orderRemove',
                data: {
                  _id: ord.result.data[0]._id
                }
              }).then(res => {
                console.log("success delete order history\n", res);
              }).catch(err => {
                console.log("fail delte order history\n", err);
              })
            }).catch(err => {
              console.error("fail remove from queue\n", err);
            });
          }).catch(err => {
            console.error("fail remove from queue\n", err);
          });

          console.log('isordered    ' + that.data.isOrdered);
          console.log('canpress     ' + that.data.canPressOrder);
          console.log('ishiden     ' + that.data.isHideOrderButton);


        } else if (res.cancel) {
          console.log('用户未取消预约')
        }
      }
    })
  },

  onClickTestSubscribe() {
    wx.requestSubscribeMessage({
      tmplIds: ["Iu3rHMGxS9JypWGqS6dzEvBYuc1d_YWDbSuUDqr_fAI"],
      success: () => {
        wx.cloud.callFunction({
          name: "sendShowerMessage",
          data: {
            openid: WXAPP.globalData.openid,
            orderID: "9234490132",
            roomID: "星A 3层10号"
          }
        }).then(res => {
          console.log("success send message ", res);
        }).catch(err => {
          console.error("Fail send message", err);
        })
      },
      fail: (err) => {
        console.error("Reject subscribe", err);
      }
    })

  },

  onClickTestShedule() {
    wx.requestSubscribeMessage({
      tmplIds: ["Iu3rHMGxS9JypWGqS6dzEvBYuc1d_YWDbSuUDqr_fAI"],
      success: () => {
        wx.cloud.callFunction({
          name: "roomSheduler"
        }).then(res => {
          console.log(res);
        }).catch(err => {
          console.error(err);
        });
      },
      fail: (err) => {
        console.error("Reject subscribe", err);
      }
    })
  },

  watchPersonCount() {
    const WATCHER = db.collection("NWPU-Queue")
      .doc(WXAPP.globalData.domitoryInfo.name)
      .watch({
        onChange: (snapshot) => {
          let queue = snapshot.docs[0][WXAPP.globalData.domitoryInfo.floor];
          console.log("queue: ", queue);
          if (this.data.isOrdered) { // 如果当前已预约，则显示前面有多少人
             if (queue.findIndex(val => val == this.data.orderID)!=0){
            this.setData({
              personCount: queue.findIndex(val => val == this.data.orderID),
              waitTime: Math.floor((queue.findIndex(val => val == this.data.orderID)  * 1.677) + Math.random() * 5)//个人洗浴平均10分钟，随机数给与缓冲时间,一层楼总共6个浴室
            });
            }
          } else { // 如果当前没预约，则显示一共预约了多少人
          if(queue.length!=0){
            this.setData({
              personCount: queue.length,
              waitTime: Math.floor(queue.length * 1.677 + Math.random() * 5)
            });
          }//都是在浴室队列不为0的时候才对前端赋值，否则保持0即可
          }
        },
        onError: (err) => {
          this.setData({
            personCount: "系统繁忙..."
          });
          console.log(err)
        }
      });
    return WATCHER;
  },

  onClickLocation() {
    if (!WXAPP.globalData.isLogin) {
      wx.showToast({
        title: '请登录后再进行定位',
        icon: 'none',
        duration: 1000
      })
    }else{
      navigateToMap();
      this.backFromMap = true;
    }
  },

  onClickMy() {
    wx.redirectTo({
      url: '../my/my',
    })
  },

  onClickFinish(){
    var that = this;
    wx.showModal({
      title: '结束洗浴',
      content: '是否结束本次洗浴？',
      success(res) {
        if (res.confirm) {
          that.setData({
            BtnOrderText: '预约',
            canPressOrder: true,
            isHideOrderButton: false,
            isOrdered: false
          });
          wx.cloud.callFunction({
            name: 'updateStatus',
            data: {
              _id: WXAPP.globalData.openid,
              canPressOrder: that.data.canPressOrder,
              isHideOrderButton: that.data.isHideOrderButton,
              isOrdered: that.data.isOrdered,
              orderNow: false
            }
          });

          db.collection('userInfo')
            .where({
              _openid: WXAPP.globalData.openid
            })
            .get()
            .then(cre => {
              wx.cloud.callFunction({
                name: 'updateCredit',
                data: {
                  _id: WXAPP.globalData.openid,
                  credit: Math.min(cre.data[0].credit + 1,3)
                }
              })
            })


          wx.cloud.callFunction({
            name: 'sortOrderHistory',
            data: {
              openid: WXAPP.globalData.openid
            }
          }).then(ord => {
            wx.cloud.callFunction({
              name: "removeFromQueue"
            }).then(res => {
              console.log("success remove from queue\n", res);
              
            }).catch(err => {
              console.error("fail remove from queue\n", err);
            });
          }).catch(err => {
            console.error("fail remove from queue\n", err);
          });

          console.log('isordered    ' + that.data.isOrdered);
          console.log('canpress     ' + that.data.canPressOrder);
          console.log('ishiden     ' + that.data.isHideOrderButton);


        } else if (res.cancel) {
          console.log('用户未结束洗浴')
        }
      }
    })
  }
})